ImageGear Java PDF > How to... > Create a PDF from an Image |
To create a PDF document from an image:
The following is an illustration of how to create PDF page from an image:
Copy Code | |
---|---|
import com.accusoft.imagegearpdf.*; import java.awt.image.BufferedImage; import java.io.*; import javax.imageio.ImageIO; class PdfDemo { private PDF pdf; private Document document; // Create a single-page PDF document from an image. public boolean createPdfPageFromImage(BufferedImage bufferedImage, double resultingWidth, double resultingHeight) { Page page = null; try { // Write the image to a buffer. ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); if (!ImageIO.write(bufferedImage, "png", outputStream)) { // The source image could not be written as a PNG image stream. return false; } // Present the image data as a memory byte array. byte[] imageData = outputStream.toByteArray(); // Create a new document with a blank page having corresponding width and height. document = pdf.createDocument(); document.insertBlankPage(0, resultingWidth, resultingHeight); // Get the page to add image to. page = document.getPage(0); // Prepare the image options. // Autosize cannot be used in this sample. Autosize calculates the height of the image internally, yet you must have the height of the image to set the Y coordinate. AddImageOptions imageOptions = new AddImageOptions(); imageOptions.setX(0); imageOptions.setY(resultingHeight); imageOptions.setWidth(resultingWidth); imageOptions.setHeight(resultingHeight); // Add an image to the page. page.addImage(imageData, imageOptions); return true; } catch (Throwable ex) { // Failed to add an image to PDF page. System.err.println("Exception: " + ex.toString()); return false; } finally { if (page != null) { // Close PDF page as it is not needed anymore. page.close(); } } } } |